<?php

namespace app\common\model\business;

use think\Model;

// 引入软删除模型
use traits\model\SoftDelete;

class Address extends Model
{
    // 调用软删除模型
    use SoftDelete;

    // 指定的数据表
    protected $name = 'business_address';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义创建时间字段
    protected $createTime = 'createtime';

    // 定义更新时间字段 => false 禁用
    protected $updateTime = false;

    // 定义软删除字段
    protected $deleteTime = 'deletetime';

    protected $append = [
        'region_text'
    ];

    public function getRegionTextAttr($value, $data)
    {
        // 区划码
        $province = $data['province'] ?? '';
        $city = $data['city'] ?? '';
        $district = $data['district'] ?? '';

        // 查询地区表
        $provinceName = model('Region')->where(['code' => $province])->value('name');
        $cityName = model('Region')->where(['code' => $city])->value('name');
        $districtName = model('Region')->where(['code' => $district])->value('name');

        $regionText = '';

        if (!empty($provinceName)) {
            $regionText .= $provinceName . '-';
        }

        if (!empty($cityName)) {
            $regionText .= $cityName . '-';
        }

        if (!empty($districtName)) {
            $regionText .= $districtName;
        }

        return $regionText ?: '未知地区';
    }

    public function provinces()
    {
        return $this->belongsTo('app\common\model\Region', 'province', 'code', [], 'LEFT')->setEagerlyType(0);
    }

    public function citys()
    {
        return $this->belongsTo('app\common\model\Region', 'city', 'code', [], 'LEFT')->setEagerlyType(0);
    }

    public function districts()
    {
        return $this->belongsTo('app\common\model\Region', 'district', 'code', [], 'LEFT')->setEagerlyType(0);
    }
}
